#!/usr/bin/env python
#coding:utf-8
import tornado.web
import tornado.gen
import json
from tornado.web import HTTPError
from datetime import datetime
from datetime import date
import hashlib
import re


class BaseHandler(tornado.web.RequestHandler):
    Status = True
    status = 200
    msg = 'ok'
    access = True


    #access登陆验证
    def __init__( self, *args, **kwargs ):
        # 继承于 tornado.web.RequestHandler
        tornado.web.RequestHandler.__init__( self, *args, **kwargs )
        self.set_header('Access-Control-Allow-Origin','http://www.lovepinyao.com')
        self.db = self.settings['db']
        self.config = self.settings['config']
        self._check_access()
        if not self.access:
            raise HTTPError(404)


    #对于请求，进行token验证
    def _check_access(self):
        #此处可以添加后期的登录控制
        if 'X-Access-Code' not in self.request.headers:
            self.access = False
        if 'X-Access-Key' not in self.request.headers:
            self.access = False

    #post方式需要验证用户权限
    @tornado.gen.coroutine
    def _check_op_access(self):
        if 'X-User-Access' not in self.request.headers:
            print(123123)
            self.access = False
        else:
            #检查session_token
            count = yield self.db.user.find({'session_token':self.request.headers['X-User-Access']}).count()
            if count == 0:
                self.access = False


    #统一返回消息接口
    @tornado.web.asynchronous
    @tornado.gen.coroutine
    def response_msg(self,code=200,msg=None,data=[],count=False):
        #设置返回的response头信息
        self.Status = False
        self.set_header("Content-Type", "application/json")
        self.set_header("Server","lovepinyao.com-Server-Group")
        self.set_default_headers()
        #组装返回信息
        responseInfo = {}
        if code:
            responseInfo['code'] = code
        if msg:
            responseInfo['message'] = msg
        if data:
            responseInfo['results'] = data
        if count:
            responseInfo['count'] = count
        self.write(json.dumps(responseInfo,cls=CJsonEncoder))
        self.finish()

    #对mongo返回的结果进行格式化，去掉ObjectId
    def find_formart(self,cousor):
        info = []
        if isinstance(cousor,dict):
            if '_id' in cousor:
                cousor['objectId'] = str(cousor['_id'])
                del cousor['_id']
            info.append(cousor)
        else:
            for e in cousor:
                e['objectId'] = str(e['_id'])
                e.pop('_id')
                info.append(e)
        return  info

    #对关键性操作进行日志备份
    def log(self,data):
        if isinstance(data,str):
            info = []
            info.append({'message':data})
        self.response_msg(200,'debug',data)


    #封装获取参数方法
    #参数存在必须和非必须2种，必须字段获取出错，直接清空返回，报错.
    #非必须字段获取出错则直接跳过
    @tornado.gen.coroutine
    def get_select_argument(self,names,unnecessary=[]):
        arguments = {}
        error = ''
        if isinstance(names,list):
            if len(names):
                for name in names:
                    try:
                        arguments[name] = self.get_argument(name)
                    except Exception as e:
                        if not error:
                            error = str(e)
        #获取非必须字段
        if len(unnecessary):
            for un in unnecessary:
               try:
                    arguments[un] = self.get_argument(un)
               except Exception as e:
                   #若在非必须字段中获取错误的话不做处理
                    pass
        #只要有错误发生，则直接清空返回
        if error:
            arguments = {}
        return (arguments,error)


    #md5加密方法
    def md5(self,str):
        m = hashlib.md5()
        m.update(str.encode())
        return m.hexdigest()

    #检查手机号码是否合法
    def phone_check(self,s):
        #号码前缀，如果运营商启用新的号段，只需要在此列表将新的号段加上即可。
        phoneprefix=['130','131','132','133','134','135','136','137','138','139','150','151','152','153','156','158','159','170','171','172','183','182','185','186','188','189']
        #检测号码是否长度是否合法。
        if len(s) != 11:
            return False
        else:
            #检测输入的号码是否全部是数字。
            if  s.isdigit():
                #检测前缀是否是正确。
                if s[:3] in phoneprefix:
                    return True
                else:
                    return False
            else:
                return False

    #检查密码的合法性
    def pass_check(self,passwd):
        if re.match(r'^(?=.*[A-Za-z])(?=.*[0-9])\w{6,20}$',passwd):
            return True
        else:
            return False


class CJsonEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime):
            return obj.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(obj, date):
            return obj.strftime('%Y-%m-%d')
        else:
            return json.JSONEncoder.default(self, obj)